package com.cq.hd.order.render;

import com.cq.hd.common.exception.BusinessException;
import com.cq.hd.order.api.vo.CreateOrderVo;
import com.cq.hd.order.render.dto.OrderResult;
import com.cq.hd.order.service.OrderCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 订单构造器
 *
 * @author much
 * @since 2024/09/11 22:07
 */
@Slf4j
@Service
public class OrderBuilder {

    @Resource
    private OrderCreateService orderCreateService;

    private final static Map<OrderRenderStepEnum, OrderRenderStep> renderStepMap = new HashMap<>();

    public static void register(OrderRenderStepEnum orderRenderStepEnum, OrderRenderStep orderRenderStep) {
        renderStepMap.put(orderRenderStepEnum, orderRenderStep);
    }

    /**
     * 创建订单
     *
     * @param orderContext 订单上下文信息
     * @return 订单信息
     */
    public OrderResult createOrder(OrderContext orderContext) {
        return null;
    }

    /**
     * 创建拼团订单
     *
     * @param orderContext 订单上下文信息
     * @return 订单信息
     */
    public CreateOrderVo createGroupBuyOrder(OrderContext orderContext) {
        renderCartBySteps(orderContext, RenderStepStatement.GROUP_BUY_ORDER);
        return orderCreateService.createGroupBuyOrder(orderContext);
    }

    /**
     * 根据渲染步骤，渲染购物车信息
     *
     * @param orderContext  订单上下文
     * @param renderSteps   渲染步骤
     */
    private void renderCartBySteps(OrderContext orderContext, OrderRenderStepEnum[] renderSteps) {
        for (OrderRenderStepEnum step : renderSteps) {
            OrderRenderStep renderStep = renderStepMap.get(step);
            if (renderStep != null) {
                try {
                    renderStep.render(orderContext);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    throw new BusinessException(e.getMessage());
                }
            } else {
                log.error("OrderRenderStep {} not exist", step);
                throw new BusinessException("创建订单失败");
            }
        }
    }

}
